﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Configuration;
using MarketPlace.Data;
using System.Web.Security;

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

namespace MarketPlace.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        public static readonly string mvcHandlerDefault = WebConfigurationManager.AppSettings["mvcHandler"];

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{exclude}/{coolite}/coolite.axd");
            routes.IgnoreRoute("Scripts/{*pathInfo}");

            bool isIIS7 = WebConfigurationManager.AppSettings["IIS"] == "7";

            string mvcHandler = isIIS7 ? string.Empty : mvcHandlerDefault;

            if (!isIIS7)
            {
                routes.MapRoute(
                    "Default",
                    "{controller}" + mvcHandler + "/{action}/{id}",
                    new { action = "Index", id = "" },
                    new string[] { "JobHunter.Web.Controllers" }
              );

                routes.MapRoute(
                  "Root",
                  "",
                  new { controller = "Home", action = "Index", id = "" },
                  new string[] { "MarketPlace.Web.Controllers" }
                );

            }
            else
            {
                routes.MapRoute(
                    "Default",                                              // Route name
                    "{controller}/{action}/{id}",                           // URL with parameters
                    new { controller = "Home", action = "Index", area = "", id = "" },  // Parameter defaults
                    new string[] { "MarketPlace.Web.Controllers" }
                );
            }
        }

        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            log.Info("Application Start");

            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            CreateRoles();

            CreateAdminUser();
        }

        protected void Application_End()
        {
            log.Info("Web application shutting down...");

            // this would be automatic, but in partial trust scenarios it is not.
            log4net.LogManager.Shutdown();
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();

            Application[HttpContext.Current.Request.UserHostAddress.ToString()] = ex;
        }

        public override string GetVaryByCustomString(HttpContext context, string custom)
        {
            if (custom == "user")
            {
                return User.Identity.IsAuthenticated ? User.Identity.Name : string.Empty;
            }
            else if (custom == "login")
            {
                return User.Identity.IsAuthenticated ? "user" : "guest";
            }
            else if (custom == "role")
            {
                if (User.IsInRole(RoleNames.TrialUser))
                {
                    return RoleNames.TrialUser.ToString();
                }
                else if (User.IsInRole(RoleNames.Member))
                {
                    return RoleNames.Member.ToString();
                }
                else if (User.IsInRole(RoleNames.Admin))
                {
                    return RoleNames.Admin.ToString();
                }
            }

            return base.GetVaryByCustomString(context, custom);
        }

        private void CreateRoles()
        {
            if (!Roles.Enabled)
            {
                return;
            }

            foreach (var r in RoleNames.AllRoles)
            {
                if (!Roles.RoleExists(r))
                {
                    Roles.CreateRole(r);
                }
            }
        }

        private void CreateAdminUser()
        {
            if (!Roles.Enabled)
            {
                return;
            }

            MembershipUser admin = Membership.GetUser(RoleNames.DefaultAdministratorName);

            if (null == admin)
            {
                MembershipCreateStatus status = MembershipCreateStatus.ProviderError;
                admin = Membership.CreateUser(RoleNames.DefaultAdministratorName, "197897[]", "1wdlcn@gmail.com", "???", "!!!", true, out status);
                if (status != MembershipCreateStatus.Success)
                {
                    log.Error("Create Default Admin Failed," + status.ToString());
                    return;
                }
            }

            if (null != admin && !Roles.IsUserInRole(admin.UserName, RoleNames.Admin))
            {
                Roles.AddUserToRole(admin.UserName, RoleNames.Admin);
            }
        }
    }
}